package su.jet.irc.server.service;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

import su.jet.common.irc.domain.User;
import su.jet.common.irc.protocol.Session;
import su.jet.common.irc.protocol.request.AuthRequest;
import su.jet.common.irc.protocol.request.LogoutRequest;
import su.jet.common.irc.protocol.request.Request;

public class RequestHandler implements Runnable{

	private Session session;
	private Set<User> regUsers;
	private Map<User, Session> onlineUsers;
	private DataService dataService;
	
	public RequestHandler(Session session, Set<User> regUsers, 
			Map<User, Session> onlineUsers, DataService dataService) {
				this.session = session;
				this.regUsers = regUsers;
				this.onlineUsers = onlineUsers;
				this.dataService = dataService;
				
				//[DF] 	FIXME: http://www.ibm.com/developerworks/java/library/j-jtp0618/index.html  
	}
	
	@Override
	public void run() {
		User connectedUser = null;
		try {
			while (true) {
				//[DF] XXX: Procedurally implemented code detected. It it better to reimplement
				//this logic using virtual functions in request... Not sure.
				Request clientRequest = session.recieveRequest();
				
				clientRequest.process(session, regUsers, onlineUsers, dataService);
				
				if (clientRequest instanceof AuthRequest)
					if (onlineUsers.containsKey(((AuthRequest) clientRequest).getUser()))
						connectedUser = ((AuthRequest) clientRequest).getUser();
				if (clientRequest instanceof LogoutRequest)
					break;
			}
			
		} catch (ClassNotFoundException e) {
				e.printStackTrace();
		
		} catch (IOException e) {
			System.out.printf("Client disconnected\n\n");
			if (connectedUser != null)
				onlineUsers.remove(connectedUser);
		}
	}
}